#!/usr/bin/env python3
# coding=utf-8

# 初始化配置
import numpy as np
import matplotlib.pyplot as plt
from time import time
from skimage import io


# matplotlib inline
plt.rcParams['figure.figsize'] = (15.0, 12.0)  # 设置默认尺寸
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

# 自动重装外部模块
# load_ext autoreload
# autoreload 2

from edge import conv, gaussian_kernel

# 用不同的尺寸以及sigma值来进行测试
kernel_size = 5
sigma = 1.4

# 载入图片 noised_umbr_gaussian.jpg
# ifile = 'data/雨伞-B.jpg'
ifile = 'tmp/noised_umbr_gaussian.jpg'
img = io.imread(ifile, as_gray=True)

# 生成高斯kernel
kernel = gaussian_kernel(kernel_size, sigma)
print(kernel)

# 利用kernel来对图片进行平滑
smoothed = conv(img, kernel)
io.imsave('tmp/canny/umbr_gaussed.jpg', smoothed)

'''
plt.subplot(1, 2, 1)
plt.imshow(img)
plt.title('Original image')
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(smoothed)
plt.title('Smoothed image')
plt.axis('off')

plt.show()
'''

from edge import partial_x, partial_y

# 计算平滑后的图像的差分
Gx = partial_x(smoothed)
Gy = partial_y(smoothed)

io.imsave('tmp/canny/umbr_dx.jpg', Gx)
io.imsave('tmp/canny/umbr_dy.jpg', Gy)

'''
plt.subplot(1, 2, 1)
plt.imshow(Gx)
plt.title('Derivative in x direction')
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(Gy)
plt.title('Derivative in y direction')
plt.axis('off')

plt.show()
'''
from edge import gradient

G, theta = gradient(smoothed)

if not np.all(G >= 0):
    print('Magnitude of gradients should be non-negative.')

if not np.all((theta >= 0) * (theta < 360)):
    print('Direction of gradients should be in range 0 <= theta < 360')

io.imsave('tmp/canny/umbr_gm.jpg', G)

'''
plt.imshow(G)
plt.title('Gradient magnitude')
plt.axis('off')
plt.show()
'''

from edge import non_maximum_suppression
nms = non_maximum_suppression(G, theta)

io.imsave('tmp/canny/umbr_nms.jpg', nms)

'''
plt.imshow(nms)
plt.title('Non-maximum suppressed')
plt.axis('off')
plt.show()
'''

from edge import double_thresholding

low_threshold = 0.02
high_threshold = 0.03

strong_edges, weak_edges = double_thresholding(
    nms, high_threshold, low_threshold)
assert(np.sum(strong_edges & weak_edges) == 0)

edges = strong_edges * 1.0 + weak_edges * 0.5

io.imsave('tmp/canny/umbr_strong.jpg', strong_edges)
io.imsave('tmp/canny/umbr_strong_weak.jpg', edges)

'''
plt.subplot(1, 2, 1)
plt.imshow(strong_edges)
plt.title('Strong Edges')
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(edges)
plt.title('Strong+Weak Edges')
plt.axis('off')

plt.show()
'''

from edge import get_neighbors, link_edges
edges = link_edges(strong_edges, weak_edges)

io.imsave('tmp/canny/umbr_edges.jpg', edges)

'''
plt.imshow(edges)
plt.axis('off')
plt.show()
'''

from edge import canny
# 载入图像
# img = io.imread('iguana.png', as_grey=True)

# 运行canny边缘检测器
edges = canny(img, kernel_size=5, sigma=1.4, high=0.03, low=0.02)
print(edges.shape)

io.imsave('tmp/canny/umbr_canny.jpg', edges)

'''
plt.subplot(1, 3, 1)
plt.imshow(edges)
plt.axis('off')
plt.title('Your result')
plt.show()
'''
